package com.test.daily.leetcode.y2021.m11.day1120;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @descriptions: findLHS
 * @author: Tom
 * @date: 2021/11/20 上午 10:08
 * @version: 1.0
 */
public class Code01_FindLHS {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 2, 2, 5, 2, 3, 7};
        Code01_FindLHS cf = new Code01_FindLHS();
        int ans = cf.findLHS2(arr);
        System.out.println(ans);
    }

    public int findLHS(int[] nums) {
        int ans = 0;
        Arrays.sort(nums);
        int begin = 0;
        for (int end = 0; end < nums.length; end++) {
            while (nums[end] - nums[begin] > 1) {
                begin++;
            }
            if (nums[end] - nums[begin] == 1) {
                ans = Math.max(ans, end - begin + 1);
            }
        }
        return ans;
    }

    public int findLHS2(int[] nums) {
        int ans = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        for (int num : map.keySet()) {
            if (map.containsKey(num + 1)) {
                ans = Math.max(ans, map.get(num) + map.get(num + 1));
            }

        }
        return ans;
    }
}
